package controllers;

import play.*;
import play.cache.Cache;
import play.mvc.*;

import imdb.ImdbApi;

import java.io.File;
import java.io.FilenameFilter;
import java.util.*;

import com.google.gson.JsonObject;

import jobs.DownloadStatus;

import models.*;
import jobs.DownloadStatus;

public class Application extends Controller {
	
	public static String	DOWNLOAD_DEST_DIR = Play.configuration.get("download_destinationdir").toString();
	public static String	VOD_DIR = Play.configuration.get("vodFilmsCheckDir").toString();
	
    public static void index() {
    	vod();
    }
    
    public static void imdbapi(String fileName) {
    	JsonObject imdbEntry = ImdbApi.searchByFileName(fileName);
    	renderTemplate("/application/imdb.html", imdbEntry);
    }
    
    public static void showUpload()
    {
    	render();
    }
    
    public static void downloadStatus()
    {
    	DownloadStatus downloadStatus = (DownloadStatus) Cache.get("DOWNLOAD_STATUS");
    	render(downloadStatus);
    }
    
    public static void upload(File nzbFile)
    {
    	notFoundIfNull(nzbFile);

    	File destFile = new File(Play.configuration.get("nzb_files_directory").toString() + nzbFile.getName());
    	nzbFile.renameTo(destFile);
    	nzbFile.delete();
        flash.success("Success " + nzbFile.getName());
 
        showUpload();
    }

    public static void vod() {
    	FilenameFilter flvFileNameFilter = new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return name.endsWith(".flv");
			}
		};
		File downloadDir = new File(VOD_DIR);
		File[] films = downloadDir.listFiles(flvFileNameFilter);
		Logger.info("Nb de films : " + films.length);
		List<String> filmsNames = new ArrayList<String>();
		
		for (File film : films) {
			filmsNames.add(film.getName());
		}
		
    	render(filmsNames);
    }
    
}